package com.jingdianjichi.wx.controller;

import com.jingdianjichi.wx.handler.MsgTypeHandler;
import com.jingdianjichi.wx.handler.WxMsgFactory;
import com.jingdianjichi.wx.utils.MessageUtil;
import com.jingdianjichi.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class WxController {


    @Resource
    private WxMsgFactory wxMsgFactory;
    private static final String TOKEN = "cosx";
    @RequestMapping("/hello")
    public String index() {
        return "hello world";
    }

    @GetMapping("/callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr){
        log.info("signature:{},timestamp:{},nonce:{},echostr:{}", signature, timestamp, nonce, echostr);
        String sha = SHA1.getSHA1(TOKEN, timestamp, nonce, "");
        if (sha.equals(signature)) {
            return echostr;
        }
        return "callback";
    }

    @PostMapping(value = "callback",produces = "application/xml; charset=utf-8")
    public String callback(
                           @RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature",required = false) String msgSignature){
        log.info("requestBody:{},signature:{},timestamp:{},nonce:{}", requestBody,signature, timestamp, nonce);
        Map<String, String> map = MessageUtil.parseXml(requestBody);
        //获取消息类型
        String msgType = map.get("MsgType");
        String event = map.get("Event") == null? "" : map.get("Event");
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if(!StringUtils.isEmpty( event)){
            sb.append(".").append(event);
        }
        msgType = sb.toString();

        log.info("msgType:{}", msgType);
        //工厂加策略
        MsgTypeHandler handler = wxMsgFactory.getHandler(msgType);
        if(Objects.isNull( handler)){
            return "位置信息";
        }
        String replyMsg = handler.handle(map);
        return replyMsg;
    }
}
